package case29

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"net/http"
	"sync"
)

func Test() {
	fmt.Println("🎯示例二十九：验证器-异步验证器")

	router := gin.Default()

	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("uniqueUsername", uniqueUsernameValidator)
	}

	router.POST("/check", func(c *gin.Context) {
		var req CheckUsernameRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"available": true,
			"message":   "用户名可用",
		})
	})

	router.Run(":60000")

}

type CheckUsernameRequest struct {
	Username string `json:"username" binding:"required,uniqueUsername"`
}

var (
	existingUsernames = map[string]bool{
		"admin": true,
		"user":  true,
		"test":  true,
	}
	usernameMutex sync.RWMutex
)

// 异步用户名唯一性验证器
var uniqueUsernameValidator validator.Func = func(fl validator.FieldLevel) bool {
	username, ok := fl.Field().Interface().(string)
	if !ok {
		return false
	}

	// 模拟异步检查（在实际项目中可能是数据库查询）
	usernameMutex.RLock()
	defer usernameMutex.RUnlock()

	_, exists := existingUsernames[username]
	return !exists
}
